define([
  'jquery',
  'GlobalInfo',
  'Grid',
  'FullCalendar',
  'navBar-general',
  'bootstrap',
  'jquery-ui.min'
],
function ($, GlobalInfo, Grid, Calendar) {
    var courses = null;
    var teachers = null;
    var classrooms = null;

    GlobalInfo.BlockUI("Cargando...");

    $(function () {
        GlobalInfo.CheckSession();

        if(!GlobalInfo.RequireRole(GlobalInfo.Role.COURSES, GlobalInfo.Role.READ_ACCESS)){
            $("#searchCourse").attr('disabled', 'disabled');
        }

        if(!GlobalInfo.RequireRole(GlobalInfo.Role.TEACHERS, GlobalInfo.Role.READ_ACCESS)){
            $("#searchTeacher").attr('disabled', 'disabled');
        }

        if(!GlobalInfo.RequireRole(GlobalInfo.Role.CLASSROOMS, GlobalInfo.Role.READ_ACCESS)){
            $("#searchClassroom").attr('disabled', 'disabled');
        }

        $("#searchCourse").click(function ()
        {
            var emptyCourseKey = ($('#claveMateria').val().trim() == "");
            var emptyCourseName = ($('#nombreMateria').val().trim() == "");
            var courseIdValue = ($('#claveMateria').val());
            var courseValue = ($('#nombreMateria').val());

    	    if(emptyCourseName && emptyCourseKey){
    		    document.getElementById("mensajes").innerHTML ="Favor de llenar uno de los campos de la b&uacute;squeda de cursos.";
                document.getElementById("mensajes").style.visibility ="visible";
    	    }
            
            else if(courseIdValue.length < 4 && courseValue.length< 4)
            {
                $("#mensajes").html("La informaci&oacute;n ingresada debe de contener al menos 4 letras");
                $("#mensajes").css("visibility", "visible");

            }
            else if(!emptyCourseName && !emptyCourseKey){
                GlobalInfo.BlockUI("Buscando...");
                params = {
                    sessionUUID: GlobalInfo.sessionUUID,
                    courseCode: $('#claveMateria').val(),
                    courseName: $('#nombreMateria').val()
                }

                GlobalInfo.CallWebService(
                    'CourseServices',
                    'GetCourse',
                    params,
                    GetCourseSuccessCallback,
                    GetCourseErrorCallback
                );					  
	        }
			
            else if(!emptyCourseName){
                GlobalInfo.BlockUI("Buscando...");
                params = {
                    sessionUUID: GlobalInfo.sessionUUID,
                    courseName: $('#nombreMateria').val().trim()
                }

                GlobalInfo.CallWebService(
                    'CourseServices',
                    'GetCoursesByName',
                    params,
                    GetCoursesByNameSuccessCallback,
                    GetCoursesByNameErrorCallback
                );
            }
            else if(!emptyCourseKey){
                GlobalInfo.BlockUI("Buscando...");
                params = {
                    sessionUUID: GlobalInfo.sessionUUID,
                    courseKey: $('#claveMateria').val().trim()
                }

                GlobalInfo.CallWebService(
                    'CourseServices',
                    'GetCoursesByKey',
                    params,
                    GetCoursesByKeySuccessCallback,
                    GetCoursesByKeyErrorCallback
                );
            }
        });
//		
		$("#teacherId").focus(function(){
			if(this.value.length>0){
				$("#teacherName").attr('readonly','true');
			}

		});
		
		$(document).ready(function(){
			$("#teacherName").removeAttr('readonly');
			$("#teacherId").removeAttr('readonly');
			$("#teacherName").val('');
			$("#teacherId").val('');
			$("#claveMateria").removeAttr('readonly');
			$("#nombreMateria").removeAttr('readonly');
			$("#claveMateria").val('');
			$("#nombreMateria").val('');
			$("#classroomText").val('');
		});
		
		$("#teacherId").blur(function(){
			if(this.value.length>0){
				$("#teacherName").attr('readonly','true');	
			}
			else{
				$("#teacherName").removeAttr('readonly');					
			}
		});
		
//
		$("#teacherName").focus(function(){
			if(this.value.length>0){
				$("#teacherId").attr('readonly','true');	
			}

		});
		
		$("#teacherName").blur(function(){
			if(this.value.length>0){
				$("#teacherId").attr('readonly','true');	
			}
			else{
				$("#teacherId").removeAttr('readonly');
					
			}
		});
//

		$("#claveMateria").focus(function(){
			if(this.value.length>0){
				$("#nombreMateria").attr('readonly','true');
			}
		});
		
		$("#claveMateria").blur(function(){
			if(this.value.length>0){
				$("#nombreMateria").attr('readonly','true');		
			}
			else{
				$("#nombreMateria").removeAttr('readonly');			
			}
		});
		
		$("#nombreMateria").focus(function(){
			if(this.value.length>0){
				$("#claveMateria").attr('readonly','true');
			}
		});
		
		$("#nombreMateria").blur(function(){
			if(this.value.length>0){
				$("#claveMateria").attr('readonly','true');	
			}
			else{
				$("#claveMateria").removeAttr('readonly');				
			}
		});

        $("#searchTeacher").click(function ()
        {
		    var emptyTeacherKey = ($('#teacherId').val().trim() == "");
            var emptyTeacherName = ($('#teacherName').val().trim() == "");
			
    	    if(emptyTeacherKey&& emptyTeacherName){
    			document.getElementById("mensajes").innerHTML ="Favor de llenar uno de los campos de la b&uacute;squeda de profesores.";
    			document.getElementById("mensajes").style.visibility ="visible";
    	    }
            else{
				if($('#teacherId').val() == ""){
                    GlobalInfo.BlockUI("Buscando...");
					var params = {
						sessionUUID: GlobalInfo.sessionUUID,
						teacherName: $('#teacherName').val()
					}

					GlobalInfo.CallWebService(
						'TeacherServices',
						'GetTeacherByName',
						params,
						GetTeachersByNameSuccessCallback,
						GetTeachersByNameErrorCallback
					);
				}else if($('#teacherName').val() == ""){
                    GlobalInfo.BlockUI("Buscando...");
					var params = {
						sessionUUID: GlobalInfo.sessionUUID,
						schoolId: $('#teacherId').val()
					}

					GlobalInfo.CallWebService(
						'TeacherServices',
						'GetTeacherBySchoolId',
						params,
						GetTeachersByIdSuccessCallback,
						GetTeachersByIdErrorCallback
					);
				}
            }
        });

        $("#searchClassroom").click(function ()
        {
            if($('#classroomText').val().trim() == ""){
                document.getElementById("mensajes").innerHTML ="Favor de llenar el campo de la b&uacute;squeda de salones.";
                document.getElementById("mensajes").style.visibility ="visible";
            }
            else if($('#classroomText').val().length < 4)
            {
                $("#mensajes").html("La informaci&oacute;n ingresada debe de contener al menos 4 letras");
                $("#mensajes").css("visibility", "visible");

            }
            else{
                GlobalInfo.BlockUI("Buscando...");
                var params = {
                    sessionUUID: GlobalInfo.sessionUUID,
                    classroomId: $('#classroomText').val()
                }

                GlobalInfo.CallWebService(
                    'ClassroomServices',
                    'GetClassroomCourses',
                    params,
                    GetClassroomSuccessCallback,
                    GetClassroomErrorCallback
                );
            }
        });
    });

    function GetCoursesByNameSuccessCallback(resultObj){
        if(resultObj.error() != null){
            GlobalInfo.ShowMessage(resultObj.error(), true, 0);
        }
        else if(!(resultObj.result().hasOwnProperty("Course"))){
            $("#mensajes").html("El curso que intent&oacute; buscar no existe en la base de datos");
            $("#mensajes").css("visibility", "visible");
			$("#calendar").fullCalendar('removeEvents');
			$("#gridTable").css('visibility','hidden');			
        }
        else if((resultObj.result().hasOwnProperty("Course")))
        {
			$("#gridTable").css('visibility','visible');
			$("#mensajes").css("visibility", "hidden");
			$("#calendar").fullCalendar('removeEvents');

            courses = resultObj.result().Course;
			
            AddCoursesToCalendar(courses);
        }
        GlobalInfo.UnblockUI();
    }
	
    function GetCoursesByNameErrorCallback(error){
        GlobalInfo.UnblockUI();
        GlobalInfo.ShowMessage('Ocurrió un error inesperado. Por favor intente más tarde.', true, 5000);
    }

    function GetCoursesByKeySuccessCallback(resultObj){
        if(resultObj.error() != null){
            GlobalInfo.ShowMessage(resultObj.error(), true, 0);
        }
        else if(!(resultObj.result().hasOwnProperty("Course"))){
            $("#mensajes").html("El curso que intent&oacute; buscar no existe en la base de datos");
            $("#mensajes").css("visibility", "visible");
            $("#calendar").fullCalendar('removeEvents');
            $("#gridTable").css('visibility','hidden');         
        }
        else{
            $("#gridTable").css('visibility','visible');
            $("#mensajes").css("visibility", "hidden");
            $("#calendar").fullCalendar('removeEvents');

            courses = resultObj.result().Course;

            AddCoursesToCalendar(courses);
        }

        GlobalInfo.UnblockUI();
    }
    

    function GetCoursesByKeyErrorCallback(error){
        GlobalInfo.UnblockUI();
        GlobalInfo.ShowMessage('Ocurri� un error inesperado. Por favor intente m�s tarde.', true, 5000);
    }

    function GetClassroomSuccessCallback(resultObj) {
        if(resultObj.error() != null){
            GlobalInfo.ShowMessage(resultObj.error(), true, 0);
        }
        else if(!(resultObj.result().hasOwnProperty("Course"))){
            $("#mensajes").html("El sal&oacute;n que intent&oacute; buscar no existe en la base de datos");
            $("#mensajes").css("visibility", "visible");
            $("#calendar").fullCalendar('removeEvents');
            $("#gridTable").css('visibility','hidden');         
        }
        else{
            $("#gridTable").css('visibility','visible');
            $("#mensajes").css("visibility", "hidden");
            $("#calendar").fullCalendar('removeEvents');

            courses = resultObj.result().Course;

            AddCoursesToCalendar(courses);
        }
        
        GlobalInfo.UnblockUI();
    }

    function GetClassroomErrorCallback(error) {
        GlobalInfo.ShowMessage('Ocurri� un error inesperado. Por favor intente m�s tarde.', true, 5000);
    }
	
    function GetTeachersByNameSuccessCallback(resultObj) {
	    if(resultObj.error() != null){
            GlobalInfo.ShowMessage(resultObj.error(), true, 0);
        }
        else if(!(resultObj.result().hasOwnProperty("Course"))){
            $("#mensajes").html("El profesor que intent&oacute; buscar no existe en la base de datos");
            $("#mensajes").css("visibility", "visible");
            $("#calendar").fullCalendar('removeEvents');
            $("#gridTable").css('visibility','hidden');         
        }
        else{
            $("#gridTable").css('visibility','visible');
            $("#mensajes").css("visibility", "hidden");
            $("#calendar").fullCalendar('removeEvents');

            courses = resultObj.result().Course;

            AddCoursesToCalendar(courses);
        }
        
        GlobalInfo.UnblockUI();
	}

    function GetTeachersByNameErrorCallback(error){
        GlobalInfo.UnblockUI();
        GlobalInfo.ShowMessage('Ocurrió un error inesperado. Por favor intente más tarde.', true, 5000);
    }
	
	function GetTeachersByIdSuccessCallback(resultObj) {
	    if(resultObj.error() != null){
            GlobalInfo.ShowMessage(resultObj.error(), true, 0);
        }

    	else if(!(resultObj.result().hasOwnProperty("Course"))){
                $("#mensajes").html("El profesor que intent&oacute; buscar no existe en la base de datos");
                $("#mensajes").css("visibility", "visible");
    			$("#gridTable").css('visibility','hidden');	
    			$("#calendar").fullCalendar('removeEvents');
        }	
        else{
			$("#gridTable").css('visibility','visible');
			$("#mensajes").css("visibility", "hidden");
			$("#calendar").fullCalendar('removeEvents');

            courses = resultObj.result().Course;
			AddCoursesToCalendar(courses);

        }
        
        GlobalInfo.UnblockUI();
	}

    function GetTeachersByIdErrorCallback(error){
        GlobalInfo.UnblockUI();
        GlobalInfo.ShowMessage('Ocurrió un error inesperado. Por favor intente más tarde.', true, 5000);
    }

    function AddCoursesToCalendar(courses){
        var eventColorMatrix = ['eventColorGreen','eventColorBlue','eventColorRed','eventColorPurple',
                                    'eventColorGreenI','eventColorBlueI','eventColorRedI','eventColorPurpleI',
                                    'eventColorGreenII','eventColorBlueII','eventColorRedII','eventColorPurpleII',
                                    'eventColorGreenIII','eventColorBlueIII','eventColorRedIII','eventColorPurpleIII'];
        var matrixCont = 0;
        var busquedas = [];
        var busquedasInactivas = [];
        var eventArray = [];
        var objArray = [];
        var cont = 0;

        for(var i = 0; i < courses.length; i++){
            if(courses[i].HasSchedule.toUpperCase() == "TRUE"){
                courses[i].Schedules.Schedule = $.isArray(courses[i].Schedules.Schedule) ? courses[i].Schedules.Schedule : [courses[i].Schedules.Schedule];
            }

            if(courses[i].HasTeacher.toUpperCase() == "TRUE"){
                courses[i].Teachers.Teacher = $.isArray(courses[i].Teachers.Teacher) ? courses[i].Teachers.Teacher : [courses[i].Teachers.Teacher];
            }
        }

        var currentDate = new Date();
        for(var i = 0; i < courses.length; i++){
            if(courses[i].HasSchedule.toUpperCase() == "TRUE"){
                for(var j = 0; j < courses[i].Schedules.Schedule.length; j++){
                    var  obj = [];
                    var contRepetidos = 0;
                    var schedule = courses[i].Schedules.Schedule[j];
                    schedule.DaysToInts.int = $.isArray(schedule.DaysToInts.int) ? schedule.DaysToInts.int : [schedule.DaysToInts.int];

                    matrixCont = ++matrixCont % eventColorMatrix.length; 
                    var busqueda = 1;
                    var Curso = [];
                    var Horario =[];
                    var Profesor =[];
                    var Salon = [];
                    var horario = "";
                    Profesor = "";
                    Salon = "";
                    Horario = "";

                    for(var k = 0; k < schedule.DaysToInts.int.length; k++){
                        var day = schedule.DaysToInts.int[k];
                        var addDays = day - currentDate.getDay();
                        var startsAt = schedule.StartsAtString.split(':');
                        var endsAt = schedule.EndsAtString.split(':');
                        Salon = schedule.Classroom.ClassroomLocation+ schedule.Classroom.ClassroomNumber;
                        
                        if(courses[i].HasTeacher.toUpperCase() == "TRUE"){
                            if(contRepetidos == 0){
                                for(var x = 0; x < courses[i].Teachers.Teacher.length; x++){
                                    Profesor +=  courses[i].Teachers.Teacher[x].Name+"<br>";
                                }
                            }
                            contRepetidos++;
                        }else{
                            Profesor = "Sin profesor";
                        }
            
                        if(contRepetidos == 1){
                            for(var x = 0; x <schedule.Days.string.length; x++){
                                if(schedule.Days.string.length > 2){
                                    horario += schedule.Days.string[x]+",";
                                }
                                else
                                    horario += schedule.Days.string[x];
                            }
                        }

                        var myEvent = {
                            id: cont,
                            title: courses[i].CourseCode+courses[i].CourseNumber+'\n'+courses[i].CourseName,
                            allDay: false,
                            start: new Date(
                              currentDate.getFullYear(),
                              currentDate.getMonth(),
                              currentDate.getDate() + addDays,
                              startsAt[0],
                              startsAt[1]
                            ),
                            end: new Date(
                              currentDate.getFullYear(),
                              currentDate.getMonth(),
                              currentDate.getDate() + addDays,
                              endsAt[0],
                              endsAt[1]
                            ),
                            className:eventColorMatrix[matrixCont],
                            displayed:true
                        };

                        $('#calendar').fullCalendar('renderEvent', myEvent);

                        eventArray.push(myEvent);
                        obj.push(myEvent);
                    }

                    objArray.push(obj);
                    cont++;

                    busqueda = 
                    {
                        Clave:      courses[i].CourseCode+courses[i].CourseNumber,
                        Curso:      courses[i].CourseName, 
                        Horario:    (horario+"."+schedule.StartsAtString+"- "+schedule.EndsAtString), 
                        Profesor:   Profesor, 
                        Salon:      Salon
                    };
                    busquedas.push(busqueda);
                }
            }
            else{
                Profesor = [];
                if(courses[i].HasTeacher.toUpperCase() == "TRUE"){
                    for(var x = 0; x < courses[i].Teachers.Teacher.length; x++){
                        Profesor +=  courses[i].Teachers.Teacher[x].Name+"<br>";
                    }
                }
                else{
                    Profesor = "Sin profesor";
                }

                busqueda = 
                {
                    Clave:      courses[i].CourseCode+courses[i].CourseNumber,
                    Curso:      courses[i].CourseName, 
                    Horario:    'Sin horario',
                    Profesor:   Profesor,
                    Salon:      'A-OFNA'
                };
                busquedasInactivas.push(busqueda);
            }
        }
        
        for(var cont = 0; cont < busquedasInactivas.length; cont++){
            busquedas.push(busquedasInactivas[cont]);
        }

        var grid = new Grid(busquedas);
        columnNames= [
                    {label:"Clave", value:"Clave"},
                    {label:"Curso", value:"Curso"},
                    {label:"Horario",value:"Horario"},
                    {label:"Profesor",value:'Profesor'},
                    {label:"Salon",value:"Salon"},
                    {label:"Acciones", value:"Acciones"}];
        grid.clear();
          
        var buttons = [];

        var showButton = $('<button/>')
                        .text('Mostrar')
                        .attr('id','mostrar')
                        .attr('name','mostrar')
                        .attr('width','50px')
                        .addClass('btn')
                        .click(
                            function(){
                                if(!eventArray[grid.selectedIndex].displayed){
                                    var objFinal = objArray[grid.selectedIndex];
                                    var selectedObj = grid.dataSource[grid.selectedIndex];
                                    for (var i = 0; i < objFinal.length; i++){
                                        $('#calendar').fullCalendar('renderEvent',objFinal[i]);
                                        eventArray[grid.selectedIndex].displayed=true;
                                    }
                                }
                            });

        var deleteButton = $('<button />')
                            .text('Quitar')
                            .attr('id',"quitar")
                            .attr('name',"quitar")
                            .addClass('btn btn-danger')
                            .click(
                                function(){
                                    if(eventArray[grid.selectedIndex].displayed){
                                        $('#calendar').fullCalendar('removeEvents',grid.selectedIndex);
                                        eventArray[grid.selectedIndex].displayed=false;
                                    }    
                            });

        buttons.push(showButton);
        buttons.push(deleteButton);

        grid.createGrid(columnNames, buttons);
        grid.excludeColumn("Acciones", FilterInactiveCourses);
    }

    function FilterInactiveCourses(obj){
        return obj.Horario == "Sin horario";
    }

    $(document).ready(function() {
        // inicializa el calendario
        $('#calendar').fullCalendar({
          defaultView: 'agendaWeek',
          minTime: '7',
          maxTime: '21',
          editable: true,        
        });
    });

    GlobalInfo.UnblockUI();
});